<template>
    <el-container class="layout-container" v-loading="loading">
        <el-aside class="layout-aside">
            <el-scrollbar>
                <div class="role-item" :class="{active: activeRole === item.role_id}" v-for="item in roles" @click="getRolePermission(item.role_id)">{{item.role_name}}</div>

            </el-scrollbar>
        </el-aside>
        <el-main class="layout-main">
            <el-header class="layout-header">
                <span>权限</span>
                <el-button type="primary" size="small" @click="saveRolePermission">保存</el-button>
            </el-header>
            <el-main class="permission-wrap">
                <el-scrollbar>
                    <div class="group" v-for="item in groupList">
                        <div>
                            <el-row class="title-row row">

                                <el-col :span="3" class="col name-col">
                                    {{item.title}}
                                </el-col>
                                <el-col :span="21" class="col checkbox-col">
                                    <el-checkbox :disabled="hasAuth" v-model="item.checkAll"
                                                 :indeterminate="item.isIndeterminate" @change="(val) => handleCheckAll(val,item)">全选</el-checkbox>
                                </el-col>
                            </el-row>
                        </div>
                        <div>

                            <el-row class="entity-row row" v-for="ite in item.entityList">

                                <el-col :span="3" class="col name-col">
                                    {{ite.function_name}}
                                    <div class="btn-wrap" v-if="ite.children && ite.children.entityList.length">
                                        <div class="btn" @click="showFieldDialog(ite.children,ite.function_name)"><i class="iconfont icon-caidan"></i></div>
                                    </div>
                                </el-col>
                                <el-col :span="3" class="col checkbox-col">
                                    <el-checkbox :disabled="hasAuth" v-model="ite.checkAll"
                                            :indeterminate="ite.isIndeterminate"
                                                 @change="(val) => handleEntityCheckAllChange(val,ite,item)"
                                    >全选</el-checkbox>
                                </el-col>
                                <el-col :span="18" class="col permision-col">
                                    <el-checkbox-group :disabled="hasAuth" v-model="ite.checked" @change="(val) => handleFieldCheckChange(val,ite,item)">
                                        <el-checkbox :disabled="hasAuth" v-for="k in checkField" :key="k" :label="k">{{k}}</el-checkbox>
                                    </el-checkbox-group>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </el-scrollbar>
            </el-main>
        </el-main>

        <el-dialog :title="dialogTitle" v-model="dialogShow">
            <div class="group">
                <div>
                    <el-row class="title-row row">

                        <el-col :span="5" class="col name-col">其他权限</el-col>
                        <el-col :span="19" class="col checkbox-col">
                            <el-checkbox :disabled="hasAuth" v-model="dialogField.checkAll"
                                         :indeterminate="dialogField.isIndeterminate" @change="(val) => handleCheckAll(val,dialogField)">全选</el-checkbox>
                        </el-col>
                    </el-row>
                </div>
                <div>

                    <el-row class="entity-row row" v-for="ite in dialogField.entityList">

                        <el-col :span="5" class="col name-col">
                            {{ite.function_name}}
                        </el-col>
                        <el-col :span="3" class="col checkbox-col">
                            <el-checkbox :disabled="hasAuth" v-model="ite.checkAll"
                                         :indeterminate="ite.isIndeterminate"
                                         @change="(val) => handleEntityCheckAllChange(val,ite,dialogField)"
                            >全选</el-checkbox>
                        </el-col>
                        <el-col :span="16" class="col permision-col">
                            <el-checkbox-group :disabled="hasAuth" v-model="ite.checked" @change="(val) => handleFieldCheckChange(val,ite,dialogField)">
                                <el-checkbox :disabled="hasAuth" v-for="k in checkField" :key="k" :label="k">{{k}}</el-checkbox>
                            </el-checkbox-group>
                        </el-col>
                    </el-row>
                </div>
            </div>
            <template #footer>
                <!--<el-button @click="dialogShow = false">取消</el-button>-->
                <el-button type="primary" @click="dialogShow = false">确定</el-button>

            </template>
        </el-dialog>
    </el-container>
</template>

<script setup>
    import {ref,reactive,onMounted,computed} from 'vue'
    import {getRole} from "../../request/api/basicData";
    import {getAuthority} from "../../utils/permission";
    import {getQXEmpty, getQXRole,updateQXRole} from "../../request/api/user";
    import pako from 'pako';
    import {unzip, deepClone} from "../../utils/utils";

    const roles = ref([]),
      activeRole = ref(''),
      checkField = ['查看', '新增', '修改', '删除',],
      groupList = ref([
        /*{
          title: '系统模块',
          entityList: [
            {
              function_name: '用户管理',
              function_id: 'user',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
              checkAll: false,
              isIndeterminate: false
            },
            {
              function_name: '角色管理',
              function_id: 'role',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_id:"permission",
              function_name:"角色权限",
              checked: [],
            },
            {
              function_name: '员工管理',
              function_id: 'employeeInf',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '公司架构',
              function_id: 'department',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '账套核算区域',
              function_id: 'zhangTaoHeSuanQuYu',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '账套操作员工',
              function_id: 'zhangTaoCaoZuoYuanGongMingXi',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '营运组',
              function_id: 'operation',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
          ]
        },
        {
          title: '基础模块',
          entityList: [
            {
              function_name: '系统参数',
              function_id: 'parameter',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '协议管理',
              function_id: 'agreement',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '证件类型',
              function_id: 'identificationType',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '站点管理',
              function_id: 'stop',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '回程接送方式',
              function_id: 'leaveSchoolType',
              fieldList: [
                // {fi,
              ],
              checked: [],
            },
            {
              function_name: '座位状态',
              function_id: 'seatStatus',
              fieldList: [
                // {field_id: '',field_name: ''}
              ]
            },
            {
              function_name: '班车方向',
              function_id: 'shuttleDirection',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '站点列表',
              function_id: 'school',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '站点类型',
              function_id: 'schoolType',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '套票类型',
              function_id: 'ticketPackageType',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '套票标签',
              function_id: 'ticketPackageLabel',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '车票类型',
              function_id: 'ticketType',
              fieldList: [
                // {field_id: '',field_name: ''}
              ],
              checked: [],
            },
            {
              function_name: '优先购票名单',
              function_id: 'EPriorityPassengers',
              checked: [],
              children:{
                entityList:  [
                  {
                    function_name: '导入',
                    function_id: 'Bulk_import',
                    checked: [],
                  },
                  {
                    function_name: '批量生成',
                    function_id: 'Bulk_add2',
                    checked: [],
                  },
                  {
                    function_name: '批量删除',
                    function_id: 'Bulk_Delete',
                    checked: [],
                  },
                ]
              },
            },
          ]
        },
        {
          title: '业务模块',
          entityList: [
            {
              function_name: '班车管理',
              function_id: 'shuttle',
              checked: [],
              children:{
                entityList:  [
                  {
                    function_name: '按营运组管理',
                    function_id: 'shuttle_operation',
                    checked: [],
                  },
                  {
                    function_name: '全量更新',
                    function_id: 'PublicAll',
                    checked: [],
                  },
                ]
              },
            },
            {
              function_name: '班车套票',
              function_id: 'shuttlePackage',
              checked: [],
            },
            {
              function_name: '班车站点',
              function_id: 'shuttleStop',
              checked: [],
            },
            {
              function_name: '班车座位',
              function_id: 'shuttleSeat',
              checked: [],
              children:{
                entityList:  [
                  {
                    function_name: '特权留位',
                    function_id: 'shuttleSeat_privileged',
                    checked: [],
                  },
                  {
                    function_name: '特权链接',
                    function_id: 'shuttleSeat_link',
                    checked: [],
                  },
                ]
              },
            },
            {
              function_name: '班车站点',
              function_id: 'shuttleSchool',
              checked: [],
            },
            {
              function_name: '订单管理',
              function_id: 'order',
              children:{
                entityList:  [
                  {
                    function_name: '导出订单',
                    function_id: 'exportOrder',
                    checked: [],
                  },
                  {
                    function_name: '导出乘车人照片',
                    function_id: 'exportPhoto',
                    checked: [],
                  },
                  {
                    function_name: '导出站点总名单',
                    function_id: 'exportSchool',
                    checked: [],
                  },
                  {
                    function_name: '导出班车去程名单',
                    function_id: 'exportGo',
                    checked: [],
                  },
                  {
                    function_name: '导出班车回程名单',
                    function_id: 'exportLeave',
                    checked: [],
                  },
                  {
                    function_name: '订单营运组限制',
                    function_id: 'order_operation_limitation',
                    checked: [],
                  },
                  {
                    function_name: '退款',
                    function_id: 'order_refund',
                    checked: [],
                  },
                ]
              },
              checked: [],
            },
            {
              function_name: '客户管理',
              function_id: 'customer',
              checked: [],
            },
            {
              function_name: '乘车人管理',
              function_id: 'passengers',
              checked: [],
            },
            {
              function_name: '后支付订单',
              function_id: 'after_payment',
              children:{
                entityList:  [
                  {
                    function_name: '后支付退款',
                    function_id: 'after_payment_refund',
                    checked: [],
                  },
                ]
              },
              checked: [],
            },
            {
              function_name: '点名班车',
              function_id: 'e_rollcall_shuttle',
              children:{
                entityList:  [
                  {
                    function_name: '可点名所有班车',
                    function_id: 'e_rollcall_shuttle_all',
                    checked: [],
                  },
                ]
              },
              checked: [],
            },
          ]
        }*/
      ]),
      //字段权限弹窗属性
      dialogTitle = ref('权限设置'),
      dialogField = ref( {}),
      dialogShow = ref(false),

      isSee = ref(true),    //可见权限
      isAppend = ref(true),    //新增权限
      isEdit = ref(true),    //编辑权限
      isDelete = ref(true),   //删除权限
      loading = ref(false)


    let hasAuth = computed( () => {
      return !(isAppend.value && isEdit.value && isDelete.value)
    })

    let roleData = [];

    prepare();

    //模块全选
    const handleCheckAll = (val,ite) => {
      ite.isIndeterminate = false;
      eachEntity(ite.entityList,val)
      /*ite.entityList.forEach(item => {
        item.isIndeterminate = false;
        item.checked = val ? checkField : []
        item.checkAll = val;
        if (item.children && item.children.entityList.length){

        }
      })*/
    }

    //模块权限全选
    const handleEntityCheckAllChange = (val,ite,par) =>{
      ite.isIndeterminate = false;
      ite.checked = val ? checkField : [];
      par.checkAll = par.entityList.every(item => item.checkAll)
      par.isIndeterminate = !par.checkAll && par.entityList.some(item => item.isIndeterminate || item.checkAll)

      if (ite.children && ite.children.entityList.length){
        ite.children.checkAll = val;
        ite.children.isIndeterminate = false;
        eachEntity(ite.children.entityList,val)
      }
    }

    //模块权限变化
    const handleFieldCheckChange = (val,ite,par) => {
      const checkedCount = val.length
      ite.checkAll = checkedCount === checkField.length
      ite.isIndeterminate = checkedCount > 0 && checkedCount < checkField.length
      par.checkAll = par.entityList.every(item => item.checkAll)
      par.isIndeterminate = !par.checkAll && par.entityList.some(item => item.isIndeterminate || item.checkAll)
    }

    //全选循环勾选
    const eachEntity = (entity,val) => {
      entity.forEach(item =>{
        item.isIndeterminate = false;
        item.checked = val ? checkField : []
        item.checkAll = val;
        if (item.children && item.children.entityList.length){
          item.children.checkAll = val;
          item.children.isIndeterminate = false;
          eachEntity(item.children.entityList,val)
        }
      })
    }

    // 初始化角色权限
    const initPermission = (data) =>{
      let tableType = {},
        children = {},
        list = [];
      // 接口数据整理
      data && data.forEach(item =>{
        let {table_type, parent_id,function_name,function_id} = item,
          checked = [],
          isIndeterminate = false,
          checkAll = false;

        item.is_see && checked.push('查看');
        item.is_append && checked.push('新增');
        item.is_edit && checked.push('修改');
        item.is_delete && checked.push('删除');
        let checkedCount = checked.length;
        isIndeterminate = checkedCount > 0 && checkedCount < checkField.length
        checkAll = checkedCount === checkField.length;

        let obj = {function_name,function_id,checked,isIndeterminate,checkAll}

        if (table_type) {
          tableType[table_type] = [...tableType[table_type] || [],obj]
        }else if (parent_id){
          children[parent_id] = [...children[parent_id] || [],obj]
        }
      });

      for (let title in tableType){
        if (tableType.hasOwnProperty(title)){
          let entityList = tableType[title];
          entityList.forEach(item =>{
            if (children[item.function_id]){
              item.children = {entityList: children[item.function_id] || []}
            }
          });
          list.push({title, entityList})
        }

      }

      console.log(list);
      groupList.value = list;
    }
    //初始化角色权限--取消固定权限
    const initPermission_v1 = (data) =>{
      groupList.forEach(item => {
        eachInitEntity(item.entityList,data)
        /*item.entityList.forEach(ite => {
          let obj = data.find(auth => auth.function_id === ite.function_id);
          ite.checked = []
          obj.is_see && ite.checked.push('查看');
          obj.is_append && ite.checked.push('新增');
          obj.is_edit && ite.checked.push('修改');
          obj.is_delete && ite.checked.push('删除');


        })*/
      })
    }

    //循环角色权限
    const eachInitEntity = (entity,data) => {
      entity.forEach(item => {
        let obj = data.find(auth => auth.function_id === item.function_id);
        item.checked = [];
        item.isIndeterminate = false;
        item.checkAll = false;
        if (!obj) return;
        obj.is_see && item.checked.push('查看');
        obj.is_append && item.checked.push('新增');
        obj.is_edit && item.checked.push('修改');
        obj.is_delete && item.checked.push('删除');
        let checkedCount = item.checked.length;
        item.isIndeterminate = checkedCount > 0 && checkedCount < checkField.length
        item.checkAll = checkedCount === checkField.length


       /* let childs = data.filter(auth => auth.parent_id === item.function_id);

        if (childs.length){
          item.children = {
            entityList: []
          }
          childs.forEach(ite => {
            let { function_name,function_id} = ite,
              checked = [],checkAll,isIndeterminate;
            ite.is_see && checked.push('查看');
            ite.is_append && checked.push('新增');
            ite.is_edit && checked.push('修改');
            ite.is_delete && checked.push('删除');
            let checkedCount = checked.length;
            isIndeterminate = checkedCount > 0 && checkedCount < checkField.length
            checkAll = checkedCount === checkField.length

            item.children.entityList.push({
              function_name, function_id, checked, checkAll, isIndeterminate
            },)
          })
        }*/
        if (item.children && item.children.entityList.length){
          eachInitEntity(item.children.entityList,data)
        }
      })
    }

    const showFieldDialog = (child,title) =>{
      console.log(child);
      // dialogField = reactive(child);
      dialogField.value = child;
      dialogTitle.value = title + '权限设置'
      dialogShow.value = true;
    }

    const getRolePermission = (id) => {
      activeRole.value = id;
      loading.value = true
      getQXRole(id).then(res => {
        loading.value = false
        let data = unzip(res.data);
        try {data = JSON.parse(data) }
        catch (e) {data = ''}

        if (data && data.root.response.errcode !== 0){
          ElMessage({
            type: 'error',
            message: data.root.response.errmsg
          });
          return
        }
        let row = data && data.root.data.row || [];
        roleData = deepClone(row);
        console.log(roleData);
        initPermission(row)
      })
      // initPermission(data)
    }

    const saveRolePermission = () => {
      let arr = [],add = [], edit = [];
      groupList.value.forEach(item => {
        each(item.entityList)
      })

      loading.value = true
      let post = {add,edit};
      updateQXRole(post).then(res =>{
        if (res.errcode !== 0){
          loading.value = false;
          return
        }
        getRolePermission(activeRole.value)
      })

      function each(entity,parId) {
        entity.forEach(item => {
          let {function_id,checked} = item,
            // isExist = roleData.some(ite => ite.function_id === function_id),
            obj = {
              role_id: activeRole.value,
              function_id,
              is_see: checked.includes('查看'),
              is_append: checked.includes('新增'),
              is_edit: checked.includes('修改'),
              is_delete: checked.includes('删除'),
            };
          parId && (obj.parent_id = parId);
          // isExist ? edit.push(obj) : add.push(obj);
          edit.push(obj);
          if (item.children && item.children.entityList) each(item.children.entityList,function_id)
        })
      }

    }

    //循环权限空表
    const initEmptyRole = (data) => {
      let arr = [];
      data.forEach(item => {
        if (item.function_type === '表') {
          arr.push({
            function_name: item.function_name,
            function_id: item.function_id,
            checked: [],
            checkAll: false,
            isIndeterminate: false,
            children: []
          })
        }
      })
    }

    function prepare(){
      let auth = getAuthority('permission');
      if (auth) {
        let {is_see,is_append,is_edit,is_delete} = auth;
        isSee.value = is_see ;
        isAppend.value = is_append;
        isEdit.value = is_edit ;
        isDelete.value = is_delete;
      }
    }

    onMounted(() =>{
      loading.value = true
      getRole({}).then(res => {
        loading.value = true
        if (res.errcode !== 0) return;
        roles.value = res.row;
        let first = res.row[0] && res.row[0].role_id;
        activeRole.value = first;
        getRolePermission(first);
      })
     /* getQXEmpty().then(res => {
        let data = unzip(res);
        try {
          data = JSON.parse(data);
        }catch (e) {
          data = ''
        }
        if (data && data.root.response.errcode !== 0){
          ElMessage({
            type: 'error',
            message: data.root.response.errmsg
          });
          return
        }
        let row = data && data.root.data.row || [],
          arr = [];
        console.log(row);
        row.forEach(item => {
          arr.push({
            function_name: '用户管理',
            function_id: 'user',
            checked: [],
            checkAll: false,
            isIndeterminate: false

          })
        })
      });*/

    })
</script>
<style scoped lang="less">
.layout-container{
    height: 100%;
    background: #ffffff;
    .layout-aside{
        padding: 10px 0;
        border-right: 1px solid #e6e6e6;
        width: 160px;
        .role-item{
            padding: 6px 10px;
            color: #4d4d4d;
            cursor: pointer;
            &:hover,&.active{
                background: #2d6ff71A;
            }
        }
    }
    .layout-header{
        /*border-bottom: 1px solid #e6e6e6;*/
        height: 38px;
        padding: 0 12px;
        line-height: 38px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}
.layout-main{
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
}
.permission-wrap{
    padding: 0 10px;
    color: #333333;
    flex: 1;
}
.title-row{
    background: #f8f8f8;
}
.entity-row{
    .name-col{
        position: relative;
        .btn-wrap{
            position: absolute;
            right: 0;
            bottom: 0;
            .btn{
                border-top: 1px solid #e6e6e6;
                border-left: 1px solid #e6e6e6;
                width: 18px;
                height: 16px;
                cursor: pointer;
                line-height: 16px;
                text-align: center;
                & > i{
                    font-size: 13px;
                    color: #000;
                }
            }
        }
    }
}
.group{
    border-top: 1px solid #e6e6e6;
    margin-bottom: 10px;
}
.col{
    padding: 0 10px;
    min-height: 30px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #e6e6e6;
    border-right: 1px solid #e6e6e6;
}
.row{
    border-left: 1px solid #e6e6e6;

}
</style>
